﻿@inject IHttpService _httpService
@inject IPopupService PopupService
@inject NavigationManager NavigationManager

<MDCard>
    <DataTableCard TModel="LotteryUserOverviewModel" Headers="_headers" ApiUrl="@(_baseUrl+Id)" ShowAddButton="false" Title="@($"{_name}列表")" @ref="dataTableCard">
        <ItemColContent>
            @if (context.Header.Value == "actions")
            {
                @if (context.Item.IsHidden)
                {
                    <MIcon Color="success"
                           Class="mr-2"
                           OnClick="()=>HideItem(context.Item,false)">@IconType.Check.ToIconString()</MIcon>
                }
                else
                {
                    <MIcon Color="error"
                           Class="mr-2"
                           OnClick="()=>HideItem(context.Item,true)">@IconType.Close.ToIconString()</MIcon>
                }
            }
            else if (context.Header.Value == nameof(LotteryUserOverviewModel.IsHidden))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.Admin.Recommends.StateChip IsHidden="@context.Item.IsHidden" />
            }
            else if (context.Header.Value == nameof(LotteryUserOverviewModel.Name))
            {
                <CnGalWebSite.Shared.MasaComponent.PC.EditRecords.UserCenter.ReviewEditRecords.UserChip Id="@context.Item.UserId" Name="@context.Item.Name" />
            }
            else
            {
                @context.Value
            }
        </ItemColContent>
        <ButtonContent>
            <CnGalWebSite.Components.Buttons.MasaButton Text="导出数据" Icon="@IconType.Export.ToIconString()" OnClick="OnExport" Class="me-4" />
            <CnGalWebSite.Components.Buttons.MasaButton Text="导入数据" Icon="@IconType.Import.ToIconString()" OnClick="OnImport" Class="me-4" />
        </ButtonContent>

    </DataTableCard>

</MDCard>
@if (export)
{
    <MDialog @bind-Value="export"
             MaxWidth="500">
        <MDCard>
            <MCardTitle Class="text-h5">
                导出抽奖数据
            </MCardTitle>
            <MCardText Style=" white-space: break-spaces;">
                @exportString
            </MCardText>
            <MCardActions>
                <MSpacer></MSpacer>
                <MButton Color="green darken-1"
                         Text
                         OnClick="()=> export = false">
                    关闭
                </MButton>
            </MCardActions>
        </MDCard>
    </MDialog>
}

<ImportCard @ref="importCard" />

@code {
    [Parameter]
    public long Id { get; set; }

    ImportCard importCard;

    bool export;
    string exportString;


    private bool _editDialog;
    private long _editedItemId;
    private bool _detailDialog;

    private string _baseUrl = "api/lotteries/ListLotteryUsers?lotteryId=";
    private string _name = "参与抽奖的用户";

    private List<DataTableHeader<LotteryUserOverviewModel>> _headers = new List<DataTableHeader<LotteryUserOverviewModel>>
    {
        new ()
          {
            Text= "Id",
            Align= DataTableHeaderAlign.Start,
            Value= nameof(LotteryUserOverviewModel.LotteryUserId)
          },
          new (){ Text= "号码", Value= nameof(LotteryUserOverviewModel.Number)},
          new (){ Text= "用户", Value= nameof(LotteryUserOverviewModel.Name)},
          new (){ Text= "Cookie", Value= nameof(LotteryUserOverviewModel.Cookie)},
          new (){ Text= "Ip", Value= nameof(LotteryUserOverviewModel.Ip)},
          new (){ Text= "状态", Value= nameof(LotteryUserOverviewModel.IsHidden)},
          new (){ Text= "操作", Value= "actions",Sortable=false }
    };

    DataTableCard<LotteryUserOverviewModel> dataTableCard;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }


    public async Task HideItem(LotteryUserOverviewModel model, bool isHidden)
    {
        string operationName = isHidden ? "隐藏" : "显示";
        try
        {
            var obj = await _httpService.PostAsync<HiddenLotteryModel, Result>("api/lotteries/HiddenLotteryUser", new HiddenLotteryModel { Ids = new long[] { model.LotteryUserId}, IsHidden = isHidden });

            if (obj.Successful == false)
            {
                await PopupService.ToastAsync(operationName + "失败", AlertTypes.Error);
            }
            else
            {

                await PopupService.ToastAsync(operationName + "成功", AlertTypes.Success);
                dataTableCard.GetDataFromApi();

            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, operationName + "失败");
        }
    }

  
    public async Task OnExport()
    {
        try
        {
            var data = await _httpService.GetAsync<DrawLotteryDataModel>("api/lotteries/GetLotteryData/" + Id);
            var model = new ExportLotteryDataModel();
            var prizeId = 1;
            foreach (var item in data.Awards)
            {
                for (var i = 0; i < item.TotalCount; i++)
                {
                    var prize = new ExportLotteryPrizeModel
                    {
                        id = prizeId++,
                        name = item.Name,
                        sponsor = item.Sponsor
                    };
                    model.prizes.Add(prize);

                    if (item.WinningUsers.Count > i)
                    {
                        var ticket = new ExportLotteryTicketModel
                        {
                            id = item.WinningUsers[i].Number,
                            nickname = item.WinningUsers[i].Name
                        };
                        model.tickets.Add(ticket);

                        model.winners.Add(new ExportLotteryWinnerModel
                        {
                            prizeId = prize.id.ToString(),
                            ticket = ticket.id.ToString()
                        });
                    }
                }
            }
            foreach (var item in data.NotWinningUsers)
            {
                model.tickets.Add(new ExportLotteryTicketModel
                {
                    id = item.Number,
                    nickname = item.Name
                });
            }
            exportString = Newtonsoft.Json.JsonConvert.SerializeObject(model, Newtonsoft.Json.Formatting.Indented);

            export = true;
            StateHasChanged();

        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "无法获取参加抽奖的用户列表");
        }
        export = true;
        StateHasChanged();
    }

    public Task OnImport()
    {

        importCard?.Refresh();
        return Task.CompletedTask;
    }
}
